<?php

class MessagesController extends Zend_Controller_Action
{
    public function deleteAction()
    {
        $messageRow = $this->_fetchRequestedMessage();
        $this->getHelper('acl')->assertAllowed($messageRow, 'delete');

        $form = new Application_Form_MessageDelete();
        if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
            $messageRow->delete();
            $this->_redirect($this->getHelper('url')->url(array(), 'index'));
        }
        $this->view->message = $messageRow;
        $this->view->form = $form;
    }

    public function editAction()
    {
        $messageRow = $this->_fetchRequestedMessage();
        $this->getHelper('acl')->assertAllowed($messageRow, 'edit');

        $form = new Application_Form_Message();
        $form->setDefaults($messageRow->toArray());
        if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
            $messageRow->setFromArray($form->getValues());
            $messageRow->save();
            $this->_redirect($this->getHelper('url')->url(array(), 'index'));
        }
        $this->view->form = $form;
    }

    private function _fetchRequestedMessage()
    {
        $messagesTable = new Application_Model_DbTable_Messages();
        if (!$messageRow = $messagesTable->find($this->getRequest()->getParam('id'))->current()) {
            throw new Application_Http_Exception404();
        }
        return $messageRow;
    }
}